<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .moveBox {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0;
            top: 0;
        }

        .parent {
            width: 500px;
            height: 500px;
            border: 2px solid;
            margin: auto;
            position: relative;
        }
    </style>
</head>

<body>
    <div class="parent">
        <div class="moveBox"></div>
    </div>


    <script>

        let moveBox = document.getElementsByClassName('moveBox')[0];
        let parent = document.getElementsByClassName('parent')[0];

        moveBox.onmousedown = function () {
            // let maxX = window.innerWidth - moveBox.offsetWidth,
            //     maxY = window.innerHeight - moveBox.offsetHeight;
            //最大x=父元素的宽度-子元素的宽度
            //parent.clientWidth 不包含边框的宽度
            let maxX = parent.clientWidth - moveBox.offsetWidth,
                maxY = parent.clientHeight - moveBox.offsetHeight

            document.onmousemove = function (event) {
                // let x = event.clientX - moveBox.offsetWidth / 2, 
                // y = event.clientY - moveBox.offsetHeight / 2;

                // 水平坐标=鼠标距离浏览器的窗口水平坐标-父元素距离浏览器的水平坐标-movebox宽的一半
                let x = event.clientX - parent.offsetLeft - moveBox.offsetWidth / 2,
                    y = event.clientY - parent.offsetTop - moveBox.offsetHeight / 2;
                if (x < 0) {
                    x = 0;
                }
                if (y < 0) {
                    y = 0;
                }

                if (x > maxX) {
                    x = maxX
                }
                if (y > maxY) {
                    y = maxY
                }

                moveBox.style.cssText = `
                left:${x}px;
                top:${y}px;
                `
            }

            moveBox.onmouseup = function () {
                document.onmousemove = null;
            }


        }


        // document.addEventListener('click', foo, false)

        // document.removeEventListener('click',foo)



    </script>

</body>

</html>